package com.xixi.example.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.xixi.core.rpc.model.RpcRequest;
import com.xixi.core.rpc.model.RpcResponse;
import com.xixi.core.rpc.serializer.CustomJdkSerializer;
import com.xixi.core.rpc.serializer.CustomSerializer;
import com.xixi.example.common.model.User;
import com.xixi.example.common.service.UserService;

import java.io.IOException;

/**
 * @author: zxh
 * @date: 2024/8/21 11:37
 * @description: UserService静态代理
 */
public class UserServiceProxy implements UserService {
	@Override
	public User getUser(User user) {
		// 指定序列化器
		CustomSerializer serializer = new CustomJdkSerializer();

		// 发请求
		RpcRequest rpcRequest = RpcRequest.builder()
				.serviceName(UserService.class.getName())
				.methodName("getUser")
				.parameterTypes(new Class[]{User.class})
				.args(new Object[]{user})
				.build();

		try {
			byte[] bodyBytes = serializer.serialize(rpcRequest);
			byte[] result;
			try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
					.body(bodyBytes)
					.execute()) {
				result = httpResponse.bodyBytes();
			}
			RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
			return (User) rpcResponse.getData();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public User getOtherUser() {
		return null;
	}
}
